//等待页面加载完成
$(function () {
    $(".media-body .collapse").on('show.bs.collapse', function (e) {
        let commentId = e.target.dataset.id;
        let anchor = $("#subCommentInput-" + commentId);
        if (anchor.parent().children().size() > 1) {
            return;
        }
        $.getJSON("/comment/" + commentId, function (data) {
            createSubCommentBlock(data, anchor);
        })
    })
})

function commentQuestion() {
    let questionId = $(" input[ name='questionId' ] ").val();
    let comment = $(" #comment ").val();
    let commentDto = {
        parentId: questionId,
        content: comment,
        type: 1
    }
    createComment(commentDto);
}

function commentComment(commentId) {
    let content = $("#createComment-" + commentId).val();
    let commentDto = {
        parentId: commentId,
        content: content,
        type: 0
    }
    createComment(commentDto);
}


function createComment(commentDto) {
    $.ajax({
        type: "POST",
        url: "/comment",
        data: JSON.stringify(commentDto),
        complete: function () {
            window.location.reload(true);
        },
        dataType: "json",
        contentType: "application/json"
    });
}

function createSubCommentBlock(commentList, anchor) {
    let model = $("#sumCommentModel");
    commentList.forEach((comment) => {
        let subComment = model.clone();
        subComment.find("img").attr("src", comment.user.avatarUrl);
        subComment.find(".media-heading").text(comment.user.name);
        subComment.find(".media-body p").text(comment.content);
        subComment.removeClass("none");
        subComment.addClass("subComments");
        anchor.before(subComment);
    });
}